package com.lablzh.gdxy.controller;

import com.lablzh.gdxy.common.BaseResult;
import com.lablzh.gdxy.common.ImgVO;
import com.lablzh.gdxy.common.ReturnCode;
import com.lablzh.gdxy.component.*;
import com.lablzh.gdxy.entity.*;
import com.lablzh.gdxy.repository.*;
import com.lablzh.gdxy.service.MailService;
import com.lablzh.gdxy.service.UserService;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    private BCryptPasswordEncoderUtil bCryptPasswordEncoderUtil;
    @Autowired
    private StudentRepositoty studentRepositoty;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private TeacherRepository teacherRepository;
    @Autowired
    private InstructorRepository instructorRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ResetRepository resetRepository;
    @Autowired
    MailService mailService;
@Autowired
    UserDetailsUtil userDetailsUtil;

//    @DeleteMapping("/instructor")
//    public String deleteInstructor(@RequestParam("ID") Integer id){
//        return userService.deleteInstructor(id);
//    }

    /**
     * 添加辅导员
     * @param instructor
     * @return
     */
//    @PostMapping("/instructor")
//    public String instructorRegister(@RequestBody Instructor instructor) {
//        return userService.addInstructor(instructor);
//    }

    /**
     * @param student
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @ResponseBody
    @PostMapping("/student")
    public String register(@RequestBody Student student) {
        return userService.addStudent(student);
    }

    /**
     * 添加教师
     * @param teacher
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @PostMapping("/teacher")
    public String addTeacher(@RequestBody Teacher teacher){
        return userService.addTeacher(teacher);
    }

    /**
     * 添加管理员
     * @param admin
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @PostMapping("/admin")
    public String adminRegister(@RequestBody Admin admin) {
        String username=userDetailsUtil.getUserDetails();
        Admin adminme=adminRepository.findAllByUsername(username);
        if(adminme.getIssysadmin().equals("1"))
        {
            return userService.addAdmin(admin);
        }
        return "你不是系统管理员";
    }
    /**
     * 添加辅导员
     * @param instructor
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @PostMapping("/instructor")
    public String instructorRegister(@RequestBody Instructor instructor) {
        return userService.addInstructor(instructor);
    }
    /**
     * 根据ID删除教师
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @DeleteMapping("/teacher")
    public String deleteTeacher(@RequestParam("ID") Integer id){
        return userService.deleteTeacher(id);
    }
    @PreAuthorize("hasAnyRole('admin')")

    @DeleteMapping("/student")
    public String deleteStudent(@RequestParam("ID") Integer id){
        return userService.deleteStudent(id);
    }
    @PreAuthorize("hasAnyRole('admin')")
    @DeleteMapping("/instructor")
    public String deleteInstructor(@RequestParam("ID") Integer id){
        return userService.deleteInstructor(id);
    }
    /**
     * 根据ID删除管理员
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @DeleteMapping("/admin")
    public String deleteAdmin(@RequestParam("ID") Integer id){
        String username=userDetailsUtil.getUserDetails();
        Admin adminme=adminRepository.findAllByUsername(username);
        if(adminme.getIssysadmin().equals("1"))
        {
            return userService.deleteAdmin(id);
        }
        return "你不是系统管理员";

    }
    //修改密码
    @PostMapping("/updatePassword")
    public String updatePassword(@RequestBody Password password ) {
        return userService.updatePassword(password);
    }

    /**
     * @param request
     * @param response
     * @return
     */
    //获取验证码
    @GetMapping("/getCode")
    public Object getCode(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/gif");
        /* 生成验证码字符串 */
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        String uuid = UUIDUtil.GeneratorUUIDOfSimple();

        //将验证码存入缓存
        VerifyCodeCache.setCode(uuid, verifyCode);
        int w = 111, h = 36;
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            VerifyCodeUtil.outputImage(w, h, stream, verifyCode);

            return new BaseResult(ReturnCode.SUCCESS.getCode(), ReturnCode.SUCCESS.getMessage()
                    //该字符串传输至前端放入src即可显示图片，安卓可以去掉data:image/png;base64,
                    , new ImgVO("data:image/gif;base64," + Base64Utils.encodeToString(stream.toByteArray()), uuid));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * @param user
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    //找回密码
    @PostMapping("/register/findPassword")
    public String findPassword(@RequestBody User user, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String role = user.getRole();
        String username = user.getUsername();
        String email = userService.gainEmail(role, username);
        System.out.println("+++++++++++++++++++");
        System.out.println(email);
        if (userRepository.findAllByUsername(username) == null) {
            return "用户不存在！";
        }
//        String path = request.getContextPath();//
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
//        String basePath="http://localhost:8081/#/";//
//        String url = userService.generateUrl(basePath, email, username);
        String password;
        switch (role) {
            case "admin":{
                Admin admin = adminRepository.findAllByUsername(username);
                password = admin.getPassword();
                break;
            }
            case "teacher":{
                Teacher teacher = teacherRepository.findAllByUsername(username);
                password = teacher.getPassword();
                break;
            }
            case "student":{
                Student student = studentRepositoty.findAllByStID(username);
                password = student.getPassword();
                break;
            }
            case "instructor" :{
                Instructor instructor = instructorRepository.findAllByUsername(username);
                password = instructor.getPassword();
                break;
            }
            default:{
                password = "未查找到你的相关信息";
            }
        }
        mailService.sendSimpleMail(email, "密码找回", "您的密码为" + password + ";该邮件30分钟内有效，请尽快处理！");
        return "邮件已发送";
    }

    /**
     * @param sid
     * @param username
     * @return
     */
    @PostMapping("/register/edit_password")
    public String verifyUrl(@RequestParam("sid") String sid, @RequestParam("username") String username) {
//        String sid1=sid.replaceAll(" ","+");
        Reset reset = resetRepository.findByUsername(username);

        if (reset == null) {
            return "false";
        }
        String sid2 = reset.getSid();
        long outTime = reset.getOutTime();
        long nowtime = System.currentTimeMillis();
        if (outTime <= nowtime) {
            return "时间过期";
        }
        if (!sid.equals(sid2)) {
            return "sid不同";
        }
        return sid;
    }



    /**
     * @param password
     * @param username
     * @param sid
     * @return
     */
    @PostMapping("/register/reset_password")
    public String resetPassword(@RequestParam("password") String password
            , @RequestParam("username") String username
            , @RequestParam("sid") String sid) {
        Reset reset = resetRepository.findByUsername(username);
        if (reset == null)
        {
            return "false";
        }
        String sid2 = reset.getSid();
        long outTime = reset.getOutTime();
        long nowtime = System.currentTimeMillis();
        if (outTime <= nowtime) {
            return "时间过期";
        }
        if (!sid.equals(sid2)) {
            return "sid不同";
        }
        User user = userRepository.findAllByUsername(username);
        user.setPassword(bCryptPasswordEncoderUtil.encode(password));
        userRepository.save(user);
        return "修改成功！";
    }

    /**
     * 学生批量导入
     * @param request
     * @return
     * @throws IOException
     * @throws FileUploadException
     */
    @PreAuthorize("hasAnyRole('admin')")
    @PostMapping("/studentBatch")
    public String studentBatch(HttpServletRequest request) throws IOException, FileUploadException {
        return userService.studentBatch(request);
    }

    /**
     * 教师批量导入
     * @param request
     * @return
     * @throws IOException
     * @throws FileUploadException
     */
    @PreAuthorize("hasAnyRole('admin')")
    @PostMapping("/teacherBatch")
    public String teacherBatch(HttpServletRequest request) throws IOException, FileUploadException {
        return userService.teacherBatch(request);
    }

    /**
     * 助教批量导入（未实现）
     * @param request
     * @return
     */
    @PreAuthorize("hasAnyRole('admin')")
    @PostMapping("/assistantBatch")
    public String assistantBatch(HttpServletRequest request)throws IOException, FileUploadException {
        return userService.assistantBatch(request);
    }


    /**
     * 考试座位安排
     * @param number
     * @param classroom
     * @param request
     * @param response
     * @return
     * @throws FileNotFoundException
     */
    @GetMapping("/arrangeSeat")
    public String arrangeSeat(@RequestParam("number") Integer number,
                              @RequestParam("classroom") String classroom,
                              HttpServletRequest request,
                              HttpServletResponse response) throws FileNotFoundException {
        return userService.arrangeSeat(number,classroom,request,response);
    }
    @PostMapping("/register/signin")
    public String signin(

            ){

        String username="admin";
        String password="123456";
        User user=new User();

        user.setPassword(bCryptPasswordEncoderUtil.encode(password));
        user.setUsername(username);
        user.setRole("admin");
        userRepository.save(user);
System.out.print("123456");
        return "注册成功";
    }
}
